package com.xilihui.xlh.core.util;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;

/**
 * 2017/3/1.
 */

public class CacheUtil {

    private static final String EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE";
    private static long fileLen = 0;

    /**
     * 得到缓存的大小
     *
     * @return
     */
    public static String CacheSize(Context context) {

        File filePath = getCacheDirectory(context, true);

        if (filePath == null) {
            return "0字节";
        }
        if (!filePath.exists()) {
            return "0字节";
        }
        long fileLen2 = getFileLen(filePath);
        return size(fileLen2);
    }


    /**
     * 删除缓存
     *
     * @param filePath
     */
    public static void deleteCache(File filePath) {

        if (filePath == null) {
            return;
        }
        if (!filePath.exists()) {
            return;
        }
        File[] files = filePath.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                files[i].delete();
            } else {
                deleteCache(files[i]);
//				files[i].delete();// 刪除文件夾
            }
        }
    }

    /**
     * 得到缓存路径
     *
     * @param context
     * @param preferExternal
     * @return
     */
    public static File getCacheDirectory(Context context, boolean preferExternal) {
        File appCacheDir = null;
        String externalStorageState;
        try {
            externalStorageState = Environment.getExternalStorageState();
        } catch (NullPointerException e) { // (sh)it happens (Issue #660)
            externalStorageState = "";
        } catch (IncompatibleClassChangeError e) { // (sh)it happens too (Issue #989)
            externalStorageState = "";
        }
        if (preferExternal && Environment.MEDIA_MOUNTED.equals(externalStorageState) && hasExternalStoragePermission(context)) {
            appCacheDir = getExternalCacheDir(context);
        }
        if (appCacheDir == null) {
            appCacheDir = context.getCacheDir();
        }
        if (appCacheDir == null) {
            String cacheDirPath = "/data/data/" + context.getPackageName() + "/cache/";
            appCacheDir = new File(cacheDirPath);
        }
        return appCacheDir;
    }

    private static File getExternalCacheDir(Context context) {
        File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
        File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
        if (!appCacheDir.exists()) {
            if (!appCacheDir.mkdirs()) {
                return null;
            }
            try {
                new File(appCacheDir, ".nomedia").createNewFile();
            } catch (IOException e) {
            }
        }
        return appCacheDir;
    }

    private static boolean hasExternalStoragePermission(Context context) {
        int perm = context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION);
        return perm == PackageManager.PERMISSION_GRANTED;
    }


    private static String size(long size) {

        if (size / (1024 * 1024 * 1024) > 0) {
            float tmpSize = (float) (size) / (float) (1024 * 1024 * 1024);
            DecimalFormat df = new DecimalFormat("#.##");
            return "" + df.format(tmpSize) + "GB";
        } else if (size / (1024 * 1024) > 0) {
            float tmpSize = (float) (size) / (float) (1024 * 1024);
            DecimalFormat df = new DecimalFormat("#.##");
            return "" + df.format(tmpSize) + "MB";
        } else if (size / 1024 > 0) {
            return "" + (size / (1024)) + "KB";
        } else
            return "" + size + "B";
    }


    private static long getFileLen(File filePath) {
        fileLen = 0;
        return getFileLenFromPath(filePath);
    }

    private static long getFileLenFromPath(File filePath) {
        File[] files = filePath.listFiles();
        if (files == null) {
            return fileLen;
        }
        for (File file : files) {
            if (file.isFile()) {
                fileLen += file.length();
            } else {
                getFileLenFromPath(file);
            }
        }
        return fileLen;
    }
}
